<?php

namespace app\model;

use think\model\concern\SoftDelete;

class ApprovalModel extends BaseModel
{
    protected $name = 'approval';


    use SoftDelete;

    /**
     * 软件删除
     *
     * @var string
     * @Author YangHB
     * @DateTime 2022-07-12 21:05:32
     *
     */
    protected $deleteTime = "deleted_at";

    public const TYPE_XS = 100;//销售订单(定制)

    public const TYPE_LIST = [
        [
            'type' => 100,
            'name' => '销售订单(定制)'
        ]
    ];


    /**
     * Notes: 创建审核节点
     * User: chenLei
     * Date: 9/7/25
     * @param $params
     * @return true
     */
    public function creates($params)
    {
        $this->save([
            'type' => $params['type'],
            'department_id' => $params['department_id'],
            'user_id' => $params['user_id'],
            'weigh' => $params['weigh'] ?? 0,
        ]);

        return true;
    }


    /**
     * Notes:  编辑审批节点
     * User: chenLei
     * Date: 9/7/25
     * @param $params
     * @return bool
     */
    public function edit($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '审批节点不存在';
            return false;
        }

        $info->save([
            'type' => $params['type'],
            'department_id' => $params['department_id'],
            'user_id' => $params['user_id'],
            'weigh' => $params['weigh'] ?? 0,
        ]);

        return true;
    }


    /**
     * Notes: 删除审批节点
     * User: chenLei
     * Date: 9/7/25
     * @param $params
     * @return bool
     */
    public function del($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '审批节点不存在';
            return false;
        }

        $info->delete();
        return true;
    }


    /**
     * Notes: 部门列表
     * User: chenLei
     * Date: 9/7/25
     * @param $parmas
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function list($parmas)
    {
        $where = [];
        if (!empty($parmas['type'])) {
            $where[] = ['type', '=', $parmas['type']];
        }

        return $this->where($where)->order('type, weigh asc,create_time asc')
            ->paginate($parmas['page_size'] ?? 15)->each(function ($item) {
                $item['department'] = UserDepartmentModel::where('id', $item['department_id'])->find();
                $item['user'] = UserModel::where('id', $item['user_id'])->field('id,username,realname')->find();
            })->toArray();
    }

}